const fs = require('fs');
const path = require('path');
const express = require('express');
var proxy = require('http-proxy-middleware');
const vueServerRenderer = require('vue-server-renderer');
const serialize = require('serialize-javascript')

const app = express();

// Server-Side Bundle File
const serverBundleFilePath = path.join(__dirname, '../dist/bundle.server.js')
const serverBundleFileCode = fs.readFileSync(serverBundleFilePath, 'utf8');
const bundleRenderer = vueServerRenderer.createBundleRenderer(serverBundleFileCode);



app.use(express.static(path.join(__dirname, '../public')))
app.use(express.static(path.join(__dirname, '../dist')))

app.get('/data', function (req, res) {
  function randNum() {
    return Math.round(Math.random() * 100);
  }
  res.send({
    name: `Hans-${randNum()}`,
    age: randNum(),
  });
});




// Server-Side Rendering
app.get('*', function (req, res) {
  console.log(req.url)
  if(req.url.indexOf('.ico')>-1){
    return ;
  }
  var context={
    url:req.url,
    cookies: req.cookies
  }
  res.setHeader("Content-Type", "text/html")
  bundleRenderer.renderToString(context,(err, html) => {
    if (err){
      res.status(500).send(`
        <h1>Error: ${err.message}</h1>
        <pre>${err.stack}</pre>
      `);
    } else {
      res.write(`<!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <title>Vue 2.0</title>
            <script src="lib/jsencrypt.js"></script>
            <link rel="stylesheet" href="css/bundle.client.css" />
          </head>
          <body>${html}
          `);
      
      if (context.initialState) {
        res.write(
          `<script>window.__INITIAL_STATE__=${
            serialize(context.initialState, { isJSON: true })
          }</script>`
        );
      }
      res.write('<script src="vendor.js"></script>')
      res.write('<script src="bundle.client.js"></script>')
      res.send(`</body></html>`);
    }
  });
});
app.use('/', proxy({
  //target: 'http://61.149.254.126:8082/drugcloud_api', 
  target:'http://192.168.3.206:8082/drugcloud_api',
  changeOrigin: true,
  logLevel: 'debug',
  headers:{},
  pathRewrite:{
    '^/apis':'/token'// /apis/XX 请求替换成/token/xx
  }
}));
module.exports=app;
